/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.ntnu.superrss.controller;

import edu.ntnu.superrss.controller.domain.FormFeed;
import edu.ntnu.superrss.models.User;
import edu.ntnu.superrss.utils.HibernateUtil;
import org.hibernate.Session;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;

/**
 *
 * @author Hallvard
 */
@Controller
@RequestMapping("/register.htm")
@SessionAttributes("user")

public class RegisterController {

    @RequestMapping(method = RequestMethod.GET)
    public String addRegisterForm(ModelMap model) {
        model.addAttribute("user", new User());
        return "register";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String processSubmit(@ModelAttribute("user") User user, ModelMap model) {
        Session sess = HibernateUtil.getSessionFactory().getCurrentSession();
        sess.beginTransaction();
        
        User tmpusr = (User) sess.createQuery("from User where username=?").setParameter(0, user.getUsername()).uniqueResult();
        if(tmpusr != null) {
            user = tmpusr;
        } else {
            sess.merge(user);
        }
        
        sess.flush();
        sess.getTransaction().commit();
//        model.addAttribute("user", user);
        model.addAttribute("formFeed", new FormFeed());

        return "redirect:feeds.htm";


    }
}
